<script setup>
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import Robot from '@/assets/svg/robot-online.svg'
import { getRobotCount } from '@/api/robot'
import {
  getAlertDetail,
  getAlertStatistics,
  getAlertStatTrend,
  reportAlert
} from '@/api/alert'
import { useAlertStore } from '@/stores'
import router from '@/router'

const localIcons = { Robot }
const getIcon = (iconName) => {
  if (localIcons[iconName]) return localIcons[iconName]
  return ElementPlusIconsVue[iconName]
}

// 统计卡片数据
const statCards = ref([
  {
    label: '今日警情',
    value: '',
    icon: 'Warning',
    type: 'warning'
  },
  {
    label: '处理中案件',
    value: '',
    icon: 'Timer',
    type: 'primary'
  },
  {
    label: '在线机器人',
    value: '',
    icon: 'Robot',
    type: 'success'
  },
  { label: '待处理报警', value: '', icon: 'Bell', type: 'danger' }
])

// 实时报警信息（未处理的最新5条）
const alerts = ref([])

// 按紧急程度和时间排序
const sortedAlerts = computed(() => {
  return [...alerts.value].sort((a, b) => {
    if (a.level === 'danger' && b.level !== 'danger') return -1
    if (a.level !== 'danger' && b.level === 'danger') return 1
    return b.time.localeCompare(a.time)
  })
})

// 分组警情，每组3条
const itemsPerGroup = 5
const groupedAlerts = computed(() => {
  const result = []
  for (let i = 0; i < sortedAlerts.value.length; i += itemsPerGroup) {
    result.push(sortedAlerts.value.slice(i, i + itemsPerGroup))
  }
  return result
})

const handleAssign = async (row) => {
  console.log(row)
  const { data } = await getAlertDetail(row.id)
  const alertStore = useAlertStore()
  alertStore.setAlertInfo(data)
  router.push('/emergency/assign')
}

// 关键指标趋势图
const trendChart = ref(null)
const trendChartData = ref({})
const initTrendChart = () => {
  const chart = echarts.init(trendChart.value)
  chart.setOption({
    title: { text: '近6个月关键指标', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: trendChartData.value.months
    },
    yAxis: [
      { type: 'value', name: '警情数量' },
      { type: 'value', name: '响应时间(min)' }
    ],
    series: [
      {
        name: '警情数量',
        type: 'line',
        data: trendChartData.value.alertCounts,
        yAxisIndex: 0
      },
      {
        name: '平均响应时间',
        type: 'line',
        data: trendChartData.value.avgResponseTimes,
        yAxisIndex: 1
      }
    ]
  })
}

const getPriorityTag = (priority) =>
  ({
    紧急: 'danger',
    警告: 'warning',
    预警: 'info'
  })[priority] || ''

const queryAlertReport = async () => {
  const { data } = await reportAlert()
  // 将信息放入alerts里面，然后每一个数据加一个level
  data.forEach((alert) => {
    alert.level = getPriorityTag(alert.emergencyLevel)
    alerts.value.push(alert)
  })
}

const queryStatCards = async () => {
  const res = await getRobotCount('IDLE')
  statCards.value[2].value = res.data

  const { data } = await getAlertStatistics()
  statCards.value[3].value = data?.pendingCount
  statCards.value[0].value = data?.todayAlertCount
  statCards.value[1].value = data?.processingCount
}

const queryAlertStatTrend = async () => {
  const { data } = await getAlertStatTrend()
  data.avgResponseTimes = data.avgResponseTimes.map((item) =>
    parseFloat(item.toFixed(2))
  )
  trendChartData.value = data
  initTrendChart()
}

onMounted(() => {
  queryStatCards()
  queryAlertStatTrend()
  queryAlertReport()
})
</script>

<template>
  <div class="dashboard-overview">
    <!-- 数据卡片区域 -->
    <section class="stat-cards">
      <el-row :gutter="24">
        <el-col :span="6" v-for="(card, index) in statCards" :key="index">
          <div class="stat-card">
            <div class="card-content">
              <el-icon class="card-icon" :class="card.type">
                <component :is="getIcon(card.icon)" />
              </el-icon>
              <div class="card-info">
                <div class="card-value">{{ card.value }}</div>
                <div class="card-label">{{ card.label }}</div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </section>

    <section class="alert-section">
      <el-card class="alert-card" shadow="none">
        <template #header>
          <div class="card-header">
            <span>实时报警信息</span>
            <el-tag type="danger" effect="dark" round
              >{{ alerts.length }}条未处理</el-tag
            >
          </div>
        </template>
        <el-carousel
          height="260px"
          :interval="3000"
          direction="vertical"
          class="alert-list"
        >
          <el-carousel-item
            v-for="(group, index) in groupedAlerts"
            :key="index"
          >
            <div class="alert-group">
              <div v-for="alert in group" :key="alert.id" class="alert-item">
                <el-icon class="alert-icon"><i-ep-Warning /></el-icon>
                <span class="alert-time">{{ alert.time }}</span>
                <span class="alert-content">{{ alert.content }}</span>
                <el-tag
                  :type="alert.level"
                  size="small"
                  round
                  class="alert-tag"
                  >{{ alert.emergencyLevel }}</el-tag
                >
                <el-button
                  type="primary"
                  size="small"
                  @click="handleAssign(alert)"
                >
                  派遣
                </el-button>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </el-card>
    </section>

    <!-- 关键指标趋势图 -->
    <section class="trend-section">
      <el-card shadow="none">
        <template #header>
          <div class="card-header">
            <span>关键指标趋势</span>
          </div>
        </template>
        <div ref="trendChart" class="chart"></div>
      </el-card>
    </section>
  </div>
</template>

<style lang="scss" scoped>
.dashboard-overview {
  padding: 2.4rem; // 减小基础内边距
  background: #f5f7fa;
  min-height: 100vh;
}

/* 数据卡片 */
.stat-cards {
  margin-bottom: 1.5rem;

  .el-row {
    flex-wrap: wrap; // 确保卡片可以换行
  }

  .stat-card {
    background: #ffffff;
    border-radius: 0.8rem;
    padding: 2rem;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    transition: transform 0.2s;
    margin-bottom: 1rem; // 添加底部间距

    &:hover {
      transform: translateY(-2px);
    }

    .card-content {
      display: flex;
      align-items: center;
      flex-wrap: wrap; // 允许内容换行

      .card-icon {
        font-size: clamp(2rem, 8vw, 4.5rem); // 自适应字体大小
        margin-right: 1rem;
        &.warning {
          color: #fa8231;
        }
        &.primary {
          color: #4834d4;
        }
        &.success {
          color: #20bf6b;
        }
        &.danger {
          color: #eb3b5a;
        }
      }

      .card-info {
        display: flex;
        align-items: center;
        gap: 1rem;
        flex: 1;

        .card-value {
          font-size: clamp(1.5rem, 6vw, 3rem);
          font-weight: 700;
          color: #1f2a44;
          line-height: 1;
        }

        .card-label {
          font-size: clamp(1rem, 4vw, 2rem);
          color: #86909c;
        }
      }
    }
  }
}

/* 报警信息 */
.alert-section {
  margin-bottom: 1.5rem;

  :deep(.el-carousel__indicator--vertical) {
    display: none;
  }

  .alert-card {
    border-radius: 0.8rem;
    background: #ffffff;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    padding: 0 1rem;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: clamp(1.2rem, 4vw, 2rem);
      font-weight: 600;
      color: #1f2a44;

      .el-tag {
        font-size: clamp(0.8rem, 3vw, 1.4rem);
        padding: 5px 10px;
      }
    }

    .alert-list {
      .alert-item {
        display: flex;
        align-items: center;
        padding: 1rem;
        border-bottom: 1px solid #f0f2f5;
        font-size: clamp(0.9rem, 3.5vw, 1.6rem);
        flex-wrap: wrap; // 允许换行

        &:hover {
          background: #f9fafc;
        }

        .alert-icon {
          color: #eb3b5a;
          margin-right: 0.5rem;
        }

        .alert-time {
          color: #86909c;
          min-width: clamp(100px, 30vw, 200px);
          margin-right: 0.5rem;
        }

        .alert-content {
          flex: 1;
          color: #1f2a44;
          margin-right: 0.8rem;
          min-width: 0; // 防止内容溢出
        }

        .el-tag {
          font-size: clamp(0.8rem, 3vw, 1.4rem);
          padding: 0 6px;
          margin: 0.3rem;
        }

        .el-button {
          font-size: clamp(0.8rem, 3vw, 1.4rem);
          background: linear-gradient(135deg, #4834d4 0%, #6b5fe8 100%);
          border: none;
          padding: 0.5rem 1rem;
        }
      }
    }
  }
}

/* 趋势图 */
.trend-section {
  margin-bottom: 1.5rem;

  .el-card {
    border-radius: 0.8rem;
    background: #ffffff;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    padding: 0 1rem;

    .card-header {
      font-size: clamp(1.2rem, 4vw, 2rem);
      font-weight: 600;
      color: #1f2a44;
    }

    .chart {
      height: clamp(25rem, 60vw, 35rem);
      width: 100%;
    }
  }
}

/* 媒体查询 */
@media screen and (max-width: 768px) {
  .stat-cards {
    .el-col {
      flex: 0 0 50%; // 每行2个卡片
      max-width: 50%;
    }
  }

  .alert-section {
    .alert-list {
      height: auto !important; // 覆盖内联样式
    }
  }
}

@media screen and (max-width: 480px) {
  .stat-cards {
    .el-col {
      flex: 0 0 100%; // 每行1个卡片
      max-width: 100%;
    }

    .card-content {
      text-align: center;

      .card-icon {
        margin-left: 2rem;
        margin-bottom: 0.5rem;
      }
      .card-info {
        justify-content: flex-end;
        margin-right: 2rem;
        .card-value {
          margin-right: 1.5rem;
        }
      }
    }
  }

  .alert-section {
    .alert-card {
      padding: 0.5rem;
    }
    .alert-item {
      // flex-direction: column;
      align-items: flex-start;

      .alert-icon {
        display: none;
      }

      .alert-tag {
        display: none;
      }

      .alert-content {
        font-size: 1.2rem;
      }

      .alert-time {
        min-width: 100%;
        font-size: 1.2rem;
      }
    }
  }

  .trend-section {
    .el-card {
      padding: 0.5rem;
    }
  }
}

/* 动画保持不变 */
.alert-item-enter-active,
.alert-item-leave-active {
  transition: all 0.3s ease;
}
.alert-item-enter-from,
.alert-item-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
</style>
